<template>
  <el-card class="w-full pt-[5px] pb0">
    <el-form :model="searchForm" class="mt-[20px]" label-width="110px" ref="searchFormRef">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="项目名称" prop="bookName">
            <el-input v-model="searchForm.bookName" placeholder="项目名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请人" prop="applierName">
            <el-input v-model="searchForm.applierName" placeholder="申请人" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属单位" prop="unitIds">
            <CustomTreeSelect
              placeholder="所属单位"
              v-model="searchForm.unitIds"
              valueKey="codeColumn"
              labelKey="valueColumn"
              :isFetch="false"
              :dataList="unitList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="flex justify-end">
            <el-button type="primary" @click="searchFormOpen = !searchFormOpen"
              >更多
              <el-icon color="#fff">
                <CaretTop v-show="searchFormOpen" />
                <CaretBottom v-show="!searchFormOpen" />
              </el-icon>
            </el-button>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-show="searchFormOpen">
        <el-col :span="6">
          <el-form-item label="评审专家" prop="expertName">
            <el-input v-model="searchForm.expertName" placeholder="评审专家" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="立项状态" prop="lixiangStates">
            <CustomTreeSelect
              :isFetch="false"
              :dataList="lxStatusList"
              placeholder="立项状态"
              v-model="searchForm.lixiangStates"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="一级学科" prop="subjectIds">
            <CustomTreeSelect
              :isFetch="false"
              :dataList="firstSubjectList"
              placeholder="一级学科"
              v-model="searchForm.subjectIds"
              valueKey="id"
              labelKey="label"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card class="w-full pt-[5px] mt-[10px]">
    <div class="mb-[20px]">
      <el-button @click="handleExport">
        <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出
      </el-button>
      <!-- <el-button>指派专家</el-button> -->
      <el-button @click="toPrevPage">返回</el-button>
    </div>
    <el-table :data="tableData" class="w-full" stripe v-loading="loading" ref="tableRef">
      <el-table-column type="selection" width="40" />
      <el-table-column label="项目名称">
        <template #default="{ row }">
          <el-link type="primary" @click="handleShow(row.bookId)">{{ row.bookName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="申请人" width="90">
        <template #default="{ row }">
          <el-link type="primary" @click="handleViewPerson(row.applierId)" v-if="row.applierId">{{
            row.applierName
          }}</el-link>
          <span v-else>{{ row.applierName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属单位" width="120">
        <template #default="{ row }">
          <CommonTreeLabel
            :value="row.unitId"
            valueKey="codeColumn"
            labelKey="valueColumn"
            :dataList="unitList"
          />
        </template>
      </el-table-column>
      <el-table-column label="一级学科" width="120">
        <template #default="{ row }">
          <CommonTreeLabel :value="row.subjectId" :dataList="firstSubjectList" />
        </template>
      </el-table-column>
      <el-table-column prop="reviewerNames" label="评审专家" width="150"/>
      <el-table-column label="评审进度" width="120">
        <template #default="{ row }">
          <el-progress
            :text-inside="true"
            :stroke-width="26"
            :percentage="parseFloat((row.processRatio * 100).toFixed(1))"
          />
        </template>
      </el-table-column>
      <el-table-column label="评审结果" width="95">
        <template #default="{ row }">
          <CustomLabel
            :map="{ pass: '建议通过', noPass: '不建议通过' }"
            :mapKey="row.reviewResult"
          />
        </template>
      </el-table-column>
      <el-table-column label="立项状态" width="90">
        <template #default="{ row }">
          <CommonLabel :dataList="lxStatusList" :value="row.projectState" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template #default="{ row }">
          <!-- 未立项且未指派专家 -->
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleAddExpert(row.bookId)"
            v-if="!row.reviewerIds && row.projectState === '0'"
          >
            指派专家
          </el-button>
          <!-- 未评审且已指派专家 -->
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleEditExpert(row.bookId)"
            v-if="row.reviewerIds && row.reviewResult === ''"
          >
            调整专家
          </el-button>
          <!-- 评审计划状态为已停止并且评审状态为建议通过并且立项状态为未立项 -->
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleLx(row.bookId, 2)"
            v-if="
              row.planStatus == 'stop' && row.reviewResult === 'pass' && row.projectState === '0'
            "
          >
            批准立项
          </el-button>
          <!-- 评审计划状态为已停止并且立项状态为已立项 -->
          <el-button
            type="warning"
            size="small"
            plain
            @click="handleLx(row.bookId, 0)"
            v-if="row.planStatus == 'stop' && row.projectState === '2'"
          >
            撤销立项
          </el-button>
          <!-- 指派了专家才展示意见汇总 -->
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleSuggest(row.bookId)"
            v-if="row.reviewerIds"
            >意见汇总</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-[20px] flex justify-end">
      <el-pagination
        v-bind="pagination"
        @update:current-page="currentChange"
        @update:page-size="sizeChange"
      />
    </div>
  </el-card>
  <ViewModal ref="viewModalRef" v-if="viewModalVisible" />
  <EditExpertModal ref="editExpertModalRef" @save-success="search" />
  <EditSuggestModal ref="editSuggestModalRef" @save-success="search" />
  <PersonView ref="personViewModalRef" />
  <exportModal
    v-model="exportVisible"
    :selectList="exportFieldList"
    :title="exportTitle"
    @callBack="handleSelectOk"
  />
</template>

<script setup>
import useTable from "@/hooks/useTable";
import { getList, exportRecords, changeLxType } from "@/api/project/xj/xmps/psxm";
import { exportFields } from "@/api/project/xj/sbxm/sbcl";
import ViewModal from "@/views/project/xj/sbxm/sbcl/components/ViewModal.vue";
import exportModal from "@/components/export";
import PersonView from "@/views/project/components/PersonView.vue";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import CustomLabel from "@/views/project/components/CustomLabel.vue";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import CommonTreeLabel from "@/views/project/components/CommonTreeLabel.vue";
import EditExpertModal from "./components/EditExpertModal.vue";
import EditSuggestModal from "./components/EditSuggestModal.vue";
import useCommonFetch from "@/hooks/useCommonFetch";
import { downloadFile } from "@/utils/main";
import { useRoute, useRouter } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";
const route = useRoute();
const router = useRouter();
const id = route.query.id;
const status = route.query.status;
const unitList = useCommonFetch("成果归属单位");
const lxStatusList = useCommonFetch("立项状态");
const firstSubjectList = useCommonFetch("一级学科");
const searchFormOpen = ref(false);
const tableRef = ref();
const searchFormRef = ref();
const viewModalRef = ref();
const viewModalVisible = ref(false);
const editExpertModalRef = ref();
const editSuggestModalRef = ref();
const exportVisible = ref(false);
const personViewModalRef = ref();
const exportFieldList = ref([]);
const exportTitle = "基本科研业务费项目申报材料";
const searchForm = ref({
  bookName: "",
  applierName: "",
  unitIds: [],
  expertName: "",
  lixiangStates: [],
  subjectIds: [],
});
//地址栏项目状态参数不为空 则已传递的立项状态默认检索
if (status) {
  searchForm.value.lixiangStates.push(status);
}
const { loading, pagination, sizeChange, currentChange, tableData, search } = useTable((pagin) =>
  getList({
    pageNum: pagin.pageNum,
    pageSize: pagin.pageSize,
    infoId: id,
    ...searchForm.value,
  })
);
//返回
const toPrevPage = () => {
  router.push("/project/xj/xmps/index");
};
//指派专家
const handleAddExpert = (id) => {
  editExpertModalRef.value.edit(id, 0);
};
//调整专家
const handleEditExpert = (id) => {
  editExpertModalRef.value.edit(id, 1);
};
//意见汇总
const handleSuggest = (id) => {
  editSuggestModalRef.value.edit(id);
};
//立项
const handleLx = async (bookId, status) => {
  const message =
    status == 2
      ? "确定要批准立项吗？"
      : "撤销立项后将同时删除已立项项目，无法恢复！确定要撤销立项吗？";
  try {
    ElMessageBox.confirm(message, "提示", {
      type: "warning",
    }).then(async () => {
      const params = {
        bookId,
        projectState: status, //2 立项  0取消立项
      };
      const res = await changeLxType(params);
      if (res.code == 200) {
        ElMessage({
          message: "操作成功！",
          type: "success",
        });
        search();
      }
    });
  } catch (error) {
    console.log(error);
  }
};
//点击名称
const handleShow = (id) => {
  viewModalVisible.value = true;
  nextTick(() => {
    viewModalRef.value.view(id);
  });
};
//点击人员姓名
const handleViewPerson = (id) => {
  personViewModalRef.value.view(id);
};
//获取导出字段
const getExportFileds = async () => {
  try {
    const params = {
      page: "review",
    };
    const res = await exportFields(params);
    if (res.code == 200) {
      const defaultCheckedList = [
        "projectCode",
        "projectName",
        "applierName",
        "applyFee",
        "applyDate",
        "projectState",
        "unitName",
        "subject",
      ];
      res.data.forEach((item) => {
        exportFieldList.value.push({
          lable: item.showName,
          value: item.field,
          isSelect: defaultCheckedList.includes(item.field) ? true : false,
        });
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//点击导出按钮
const handleExport = async () => {
  //exportFieldList为空时才获取数据
  if (!exportFieldList.value.length) {
    await getExportFileds();
  }
  exportVisible.value = true;
};
//导出字段选择完毕
const handleSelectOk = async (val) => {
  const cols = val.map((item) => item.prop);
  try {
    const params = {
      ...searchForm.value,
      infoId: id,
      cols,
    };
    const res = await exportRecords(params);
    if (res.type != "application/json") {
      downloadFile(res, exportTitle + ".xlsx");
    }
  } catch (error) {
    console.log(error);
  }
};
const resetForm = () => {
  searchFormRef.value.resetFields();
  search();
};
</script>

<style scoped lang="scss"></style>
